# -*- coding: utf-8 -*-
import json
import logging
import re
from COMPARE import get_back_data
from MAPPING import dump_to_json
from commens import reMML

data = None



def map_param(param):
    p = {}
    for k, v in param.items():
        if k == '参数说明':
            for i in range(0, len(attrReList)):
                res = attrReList[i].search(v)
                if res:
                    p[attrList[i]] = res[1]
                else:
                    p[attrList[i]] = None
        else:
            p[k] = v
    return p


def get_param_list(params):
    return [map_param(x) for x in params]


def parse_data(data):
    newData = {}
    for k, v in data.items():
        if '参数说明' in v.keys():
            newData[k] = get_param_list(v['参数说明'])
        else:
            newData[k] = None
    return newData


def addOutParam(oldData):
    global data
    out = get_back_data('OUTPARAM.json')
    for mml,plist in out.items():
        if mml in oldData.keys():
            if('输出结果说明' in data[mml].keys()):
                outputResultDic = strToDict(mml,data[mml]['输出结果说明'])
                if outputResultDic:
                    for outputParam in plist:
                        if outputParam['参数名称'] in outputResultDic.keys():
                            outputParam['参数含义'] = outputResultDic[outputParam['参数名称']]
            oldData[mml]=oldData[mml]+plist if oldData[mml] is not None else plist
        else:
            print('%s miss'%mml)



def main():
    global data
    data = get_back_data()
    newData = parse_data(data)
    # 注释下面这行以恢复更改
    addOutParam(newData)
    dump_to_json(newData,'PARAM.json')
    print('共处理了%d条数据'%len(newData))


def strToDict(title,str):
    if str.find('参见')!=-1:
        logPARAM.debug(f'◆{title}没有输出结果说明表')
        needlookMMLList = reMML.findall(str)
        if needlookMMLList:
            logPARAM.debug(f'要求参见 {needlookMMLList}')
    str = str.strip('\n\t ')
    tempList = str.split(' ')
    tempDict = dict(zip(tempList[0::2], tempList[1::2]))
    return tempDict


if __name__ == '__main__':
    attrList = ['参数含义', '取值范围', '配置原则']
    attrReList = [re.compile(x + r'：(.*)\n') for x in attrList]
    logPARAM = logging.getLogger("PARAM")
    logPARAM.setLevel(logging.DEBUG)
    hdPARAM = logging.FileHandler("PARAM.log", mode='w', encoding='utf-8')
    ch = logging.StreamHandler()
    ch.setLevel(logging.WARNING)
    hdPARAM.setLevel(logging.DEBUG)
    logPARAM.addHandler(hdPARAM)
    logPARAM.addHandler(ch)
    main()


